<?php
class CommentController extends BaseController {
	
	//评论列表
	public function indexAction($params) {
		$wheresql = '1';
		$page = max(1, intval($params['page']));
		$pagesize = 10;
		$offset = ($page - 1) * $pagesize;
		$url = '?mod=comment';
		
		//类型过滤
		if ( $params['filter'] == 'unchk' ) {
			$wheresql .= " AND c.`status` = 0";
			$url .= '&filter='.$params['filter'];
		}
		//关键字查找
		if (isset($params['keyword']) && !empty($params['keyword'])) {
			$keyword = str_replace(array('%','_'), array('\%','\_'), $params['keyword']);
			$wheresql .= " AND (c.content LIKE '%$keyword%' OR c.author LIKE '%$keyword%' OR c.email LIKE '%$keyword%')";
			$url .= '&keyword='.rawurlencode($keyword);
		}
		//指定文章的评论
		if ( isset($params['postid']) && is_numeric($params['postid']) ) {
			$wheresql .= " AND c.postid = '{$params['postid']}'";
			$url .= "&postid={$params['postid']}";
		}
		
		$count = $this->db->count('comment c', $wheresql);
		$list = array();
		if ( $count ) {
			$query = $this->db->query("SELECT c.*, p.title, p.dateline AS posttime 
					FROM ".$this->db->tname('comment')." c LEFT JOIN ".$this->db->tname('post')." p ON c.postid = p.id
					WHERE $wheresql ORDER BY c.id DESC LIMIT $offset, $pagesize");
			while ( $row = $this->db->fetch_array($query) ) {
				$list[] = $row;
			}
		}
		$this->assign('list', $list);
		$this->display();
	}
	
	//审核评论
	public function auditAction($params) {
		
	}
	
	//编辑评论
	public function editAction($params) {
		if ($this->input->isPost()) {
			$id = intval($this->input->get('id'));
			$updata = $this->input->get('comment');
			$comment = new Comment($id);
			if ($comment->exists) {
				foreach ($updata as $key => $value) {
					$comment->{$key} = $value;
				}
				if (!$comment->save()) {
					$this->prompt($comment->error());
				} else {
					$this->redirect($this->refer);
				}
			}
		} else {
			$comment = new Comment(intval($params['id']));
			if (!$comment->exists) {
				$this->prompt(__('评论不存在'));
			}
			$this->assign('comment', $comment->toObject());
			$this->display();
		}
	}
	
	//回复评论
	public function replyAction($params) {
		
	}
	
	//删除评论
	public function deleteAction($params) {
		$ids = $this->input->get('ids');
		if (empty($ids)) $ids = $this->input->get('id');
		if ($ids) {
			foreach ((array)$ids as $id) {
				if (is_numeric($id)) {
					$this->doDel($id);
				}
			}
		}
		$this->redirect($this->refer);
	}
	
	/**
	 * 删除一条评论及其关联信息
	 * @param int $id
	 */
	private function doDel($id) {
		
	}
}